package com.situ.company.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.situ.company.entity.User;

//@WebFilter(filterName = "/loginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter{

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		
		String uri = httpServletRequest.getRequestURI();
		System.out.println("uri: " + uri);
		String servletPath = httpServletRequest.getServletPath();
		System.out.println("servletPath: " + servletPath);
		// /user?method=login
		String method = httpServletRequest.getParameter("method");
		
		// 某些请求不需要验证是不是已经登录，像一些js、css的静态资源，还有要去完成登录的过程
		// 也不需要验证登录
		if ("/login.jsp".equals(servletPath)
				|| ("/user".equals(servletPath) && "login".equals(method))
				|| servletPath.endsWith(".js")
				|| servletPath.endsWith(".css")
				|| servletPath.endsWith(".png")) {
			chain.doFilter(request, response);
		} else { // 需要验证有没有登录
			HttpSession session = httpServletRequest.getSession();
			User user = (User) session.getAttribute("user");
			if (user == null) {
				httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/login.jsp");
				return;
			}
			chain.doFilter(request, response);
		}
	}

	@Override
	public void destroy() {
		
	}

}
